package com.edu.servlet;

import com.edu.bean.User;
import com.edu.service.AdminUserService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/user/*")
public class AdminUserServlet extends HttpServlet {
    private AdminUserService adminUserService = new AdminUserService();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/list":
                listUser(request, response);
                break;
            case "/get":
                getUser(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/add":
                addUser(request, response);
                break;
            case "/update":
                updateUser(request, response);
                break;
            case "/delete":
                deleteUser(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void listUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取分页参数
        int pageSize = 10; // 每页显示10条
        int currentPage = 1; // 默认第一页
        String pageStr = request.getParameter("page");
        if (pageStr != null && !pageStr.trim().isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
                if (currentPage < 1) {
                    currentPage = 1;
                }
            } catch (NumberFormatException e) {
                // 解析失败，使用默认值
            }
        }

        // 获取搜索参数
        String username = request.getParameter("username");

        // 获取总记录数和总页数
        int totalCount = adminUserService.adminGetTotalCount(username);
        int totalPages = (totalCount + pageSize - 1) / pageSize;

        // 校正当前页码
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }

        // 获取当前页的数据
        List<User> userList = adminUserService.adminListUserByPage(username, currentPage, pageSize);

        // 设置分页相关的属性
        request.setAttribute("userList", userList);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("username", username);

        request.getRequestDispatcher("/admin/user-list.jsp").forward(request, response);
    }

    private void getUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            User user = adminUserService.adminGetUserById(Integer.parseInt(idStr));
            if (user != null) {
                request.setAttribute("user", user);
                request.getRequestDispatcher("/admin/user-edit.jsp").forward(request, response);
                return;
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            request.getRequestDispatcher("/admin/user-add.jsp").forward(request, response);
        }
    }

    private void addUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            User user = new User();
            user.setUsername(request.getParameter("username"));
            user.setPassword(request.getParameter("password")); // MD5加密的密码
            user.setRoleId(Integer.parseInt(request.getParameter("roleId")));
            user.setRealName(request.getParameter("realName"));
            user.setEmail(request.getParameter("email"));

            boolean success = adminUserService.adminAddUser(user);
            result.put("success", success);
            if (!success) {
                result.put("message", "添加失败，用户名可能已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            User user = new User();
            user.setUserId(Integer.parseInt(request.getParameter("userId")));
            user.setUsername(request.getParameter("username"));
            String password = request.getParameter("password");
            if (password != null && !password.trim().isEmpty()) {
                user.setPassword(password); // MD5加密的密码
            }
            user.setRoleId(Integer.parseInt(request.getParameter("roleId")));
            user.setRealName(request.getParameter("realName"));
            user.setEmail(request.getParameter("email"));

            boolean success = adminUserService.adminUpdateUser(user);
            result.put("success", success);
            if (!success) {
                result.put("message", "更新失败，用户名可能已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            // 获取当前登录用户的ID
            User currentUser = (User) request.getSession().getAttribute("adminUser");
            boolean success = adminUserService.adminDeleteUser(Integer.parseInt(idStr), currentUser.getUserId());
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败，不能删除当前登录用户");
            }
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }
}